# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10895': {  # loki 支付宝3.5%（1---3000
        'API_KEY': '677443927f3e050722a709dd168e8d9b8861bbe5',
        'gateway': 'http://api.y3i2.cn/gateway',
    },
    '10950': {  # dwc 支付宝：3.5%（20---5000）d0结算。
        'API_KEY': '69995d012622f194561012d2e937a8f2015387f8',
        'gateway': 'http://api.y3i2.cn/gateway',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def generate_sign(d, key):
    s = 'app_id={}&content={}&method={}&version={}&key={}'.format(
        d['app_id'], d['content'], d['method'], d['version'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_notify_sign(d, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(d.keys()):
        if d[k] != '' and d[k] != None:
            s += '%s=%s&' % (k, d[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    params.pop('sign_type')
    sign = params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("yihuipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# alipay	支付宝（扫码）
# alipaywap	支付宝（手机）
# weixin	微信（扫码）
# wxh5	微信H5（手机）
# qqqb	QQ钱包
# qqrcode	手机QQ扫码
# jdqb	京东钱包（扫码）
# jdwap	京东（手机）
# ylqb	银联钱包
# quickpay	快捷支付
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'wxh5'
    elif service == 'alipay':
        payType = 'alipaywap'
    elif service == 'qq':
        payType = 'qqqb'
    elif service == 'jd':
        payType = 'jdwap'
    else:
        payType = 'quickpay'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('app_id', mch_id),
        ('method', _get_pay_type(service)),
        ('sign_type', 'MD5'),
        ('version', '1.0'),
    ))
    content = {
        'out_trade_no': str(pay.id),
        'order_name': 'charge',
        'total_amount': '%.2f' % pay_amount,
        'spbill_create_ip': _get_device_ip(info),
        'notify_url': '{}/pay/api/{}/yihuipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id),
        'return_url': '{}/pay/api/{}/yihuipay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))
    }
    parameter_dict['content'] = json.dumps(content).encode('utf8')
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    _LOGGER.info("yihuipay create data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(mch_id), data=parameter_dict, headers=headers, timeout=30)
    _LOGGER.info("yihuipay create rsp data: %s", response.text)
    cache_id = redis_cache.save_html(pay.id, response.text)
    url = settings.PAY_CACHE_URL + cache_id
    return {'charge_info': url}


# success
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("yihuipay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('yihuipay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data['trade_no']
    total_fee = float(data['total_amount'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1:为成功，其他值为失败
    if trade_status == 1:
        _LOGGER.info('yihuipay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('app_id', app_id),
        ('method', 'query'),
        ('sign_type', 'MD5'),
        ('version', '1.0'),
    ))
    content = {
        'out_trade_no': str(pay_id),
    }
    parameter_dict['content'] = json.dumps(content).encode('utf8')
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    _LOGGER.info("yihuipay query data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=30)
    _LOGGER.info("yihuipay query rsp: %s", response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['trade_status'])  # 0 订单未成功 1订单成功
        total_fee = float(data['total_amount'])
        trade_no = data['trade_no']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('yihuipay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('yihuipay data error, status_code: %s', response.status_code)
